package com.lijinjiang.listener;

import com.lijinjiang.entity.User;
import com.lijinjiang.service.UserService;
import com.lijinjiang.util.MD5Util;
import com.lijinjiang.view.MainView;
import com.lijinjiang.view.loginView;
import com.lijinjiang.view.messageDialog;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 登录界面的登录按钮监听类
 */
public class LoginView_loginButton_ActionListener implements ActionListener {
    loginView view;
    JTextField userField;
    JPasswordField passwordField;

    public LoginView_loginButton_ActionListener(loginView loginView) {
        // TODO Auto-generated constructor stub
        this.view = loginView;
        this.userField = view.getLoginUser();
        this.passwordField = view.getPasswordField();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // 获取账号
        String account = userField.getText();
        // 判断账号是否为空
        if (account == null || account.length() == 0) {
            System.out.println("输入账号为空！");
            JOptionPane.showMessageDialog(null, "账号不能为空，请输入您的账号！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        // 获得密码并且进行MD5加密
        String password = new String(passwordField.getPassword());
        String passwordMD5 = MD5Util.MD5EncodeUtf8(password);
        // 判断密码是否为空
        if (password == null || password.length() == 0) {
            System.out.println("输入密码为空！");
            JOptionPane.showMessageDialog(null, "密码不能为空，请输入您的密码！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        UserService userService = new UserService();
        User user = userService.getUserByAccount(account);
        // 判断输入的密码与用户密码是否一致
        // System.out.println(passwordMD5);
        // System.out.println(user.getPassword());
        if(user!= null && passwordMD5.equals(user.getPassword())){
            // System.out.println("密码正确！");
            //JOptionPane.showMessageDialog(null, "欢迎：" + account);
            // 设置一个显示500ms的提示框
            new messageDialog(view, "登录成功！", new Dimension(200, 60)).setVisible(true);
            new MainView(user);
            view.dispose();
        } else {
            System.out.println("账号或密码错误！");
            JOptionPane.showMessageDialog(null, "账号或密码错误，请重新登录！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}